package com.jiancong.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiancong.domain.ResponseResult;
import com.jiancong.domain.dto.AddArticleDto;
import com.jiancong.domain.entity.Article;
import com.jiancong.domain.entity.ArticleTag;
import com.jiancong.domain.entity.Category;
import com.jiancong.domain.vo.*;
import com.jiancong.enums.AppHttpCodeEnum;
import com.jiancong.mapper.ArticleMapper;
import com.jiancong.mapper.ArticleTagMapper;
import com.jiancong.mapper.CategoryMapper;
import com.jiancong.mapper.TagMapper;
import com.jiancong.service.ArticleService;
import com.jiancong.utils.BeanCopyUtils;
import com.jiancong.utils.RedisCache;
import com.jiancong.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisCache redisCache;
    @Override
    public ResponseResult hostArticleList() {

        PageHelper.startPage(1,10);
        List<Article> articles1 = articleMapper.hotArticleList();
        //把记录所有数据的集合转化为Page类型
        PageInfo<Article> pageInfo = new PageInfo<>(articles1);
        List<Article> articles = pageInfo.getList();
//        bean拷贝
        List<HotArticleVo> articleVos = new ArrayList<>();
        for (Article article : articles) {
            HotArticleVo vo = new HotArticleVo();
            BeanUtils.copyProperties(article,vo);
            articleVos.add(vo);
        }
        return ResponseResult.okResult(articleVos);
    }

    @Override
    public ResponseResult articleList(Integer pageNum, Integer pageSize, Long categoryId) {


        //articleId去查询articleName进行设置
//        List<HotArticleVo> articleVos = new ArrayList<>();
//        for (Article article : articles) {
//            HotArticleVo vo = new HotArticleVo();
//            BeanUtils.copyProperties(article,vo);
//            articleVos.add(vo);
//        }
        PageHelper.startPage(pageNum,pageSize);
//        //把记录所有数据的集合转化为Page类型
        PageInfo<ArticleListVo> pageInfo = new PageInfo<>(articleMapper.articleList(categoryId));
//        List<ArticleListVo> articleVos = new ArrayList<>();
        List<ArticleListVo> articles = pageInfo.getList();
//        for (Article article : articles) {
//            ArticleListVo vo = new ArticleListVo();
//            BeanUtils.copyProperties(article,vo);
//            Category category =
//                    categoryService.getById(article.getCategoryId());
//            vo.setCategoryName(category.getName());
//            articleVos.add(vo);
//        }

        PageVo pageVo = new PageVo(articles,pageInfo.getTotal());

        return ResponseResult.okResult(pageVo);


        //查询条件
        //如果有categoryId就要查询时要和传入的相同
        //状态是正式发布的
        //置顶的文章要放在最前面
        //对istop进行降序

        //分页查询




    }

    @Override
    public ResponseResult getArticleDetail(Long id) {
        //根据id查询文章
        Article article = articleMapper.getById(id);
        Integer viewCount = redisCache.getCacheMapValue("article:viewCount", id.toString());
        article.setViewCount(viewCount.longValue());
        ArticleDetailVo articleDetailVo = BeanCopyUtils.copyBean(article, ArticleDetailVo.class);
        Long categoryId = article.getCategoryId();
        Category category = categoryMapper.getById(categoryId);
        if(category!=null){
            articleDetailVo.setCategoryName(category.getName());
        }
        return ResponseResult.okResult(articleDetailVo);

    }




//        LambdaQueryWrapper<Article> QueryWrapper = new LambdaQueryWrapper<>();
//        //必须正文
//        QueryWrapper.eq(Article::getStatus,0);
//        //按照浏览量进行排序
//        QueryWrapper.orderByDesc(Article::getViewCount);
//        //最多只查询10条
//        Page<Article> page = new Page(1,10);
//        page(page,QueryWrapper);
//        List<Article> articles = page.getRecords();
//        return ResponseResult.okResult(articles);

    @Override
    @Transactional
    public ResponseResult updateViewCount(Long id) {
        //更新redis中对应 id的浏览量
        redisCache.incrementCacheMapValue("article:viewCount",id.toString(),1);
        return ResponseResult.okResult();

    }

    @Autowired
    private ArticleTagMapper articleTagMapper;
    @Autowired
    private SensitiveWordLoader sensitiveWordLoader;
    @Override
    @Transactional
    public ResponseResult add(AddArticleDto articleDto) {

        //添加 博客

        Set<String> sensitiveWords = sensitiveWordLoader.getSensitiveWords();
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        List<String> fieldsToCheck = Arrays.asList(
                article.getContent(),
                article.getTitle(),
                article.getSummary()
        );

        Long userId = SecurityUtils.getUserId();
        article.setCreateBy(userId);
        article.setUpdateBy(userId);
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());
        // 遍历敏感词和字段
        for (String word : sensitiveWords) {
            for (String field : fieldsToCheck) {
                if (field.contains(word)) {
                    article.setStatus("1");
                }
            }
            articleMapper.save(article);
            List<ArticleTag> articleTags = new ArrayList<>();
            for (Long tagId : articleDto.getTags()) {
                ArticleTag articleTag = new ArticleTag(article.getId(), tagId);
                articleTags.add(articleTag);
            }
            //添加 博客和标签的关联
            articleTagMapper.saveBatch(articleTags);
            return ResponseResult.okResult("文章审核不通过");
        }
        articleMapper.save(article);
        List<ArticleTag> articleTags = new ArrayList<>();
        for (Long tagId : articleDto.getTags()) {
            ArticleTag articleTag = new ArticleTag(article.getId(), tagId);
            articleTags.add(articleTag);
        }
        //添加 博客和标签的关联
        articleTagMapper.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult getArticles(Integer pageNum, Integer pageSize, ArticleVo articlevo) {
        PageHelper.startPage(pageNum,pageSize);
        //把记录所有数据的集合转化为Page类型
        Long userId = SecurityUtils.getUserId();
        if (!userId.equals(1)){
            PageInfo<ArticleVo> pageInfo = new PageInfo<>(articleMapper.getArticlesById(articlevo,userId));
            List<ArticleVo> tagVos = pageInfo.getList();
            PageVo pageVo = new PageVo(tagVos,pageInfo.getTotal());
            return ResponseResult.okResult(pageVo);
        }
        PageInfo<ArticleVo> pageInfo = new PageInfo<>(articleMapper.getArticles(articlevo));
        List<ArticleVo> tagVos = pageInfo.getList();
        PageVo pageVo = new PageVo(tagVos,pageInfo.getTotal());
        return ResponseResult.okResult(pageVo);
    }




    @Autowired
    private TagMapper tagMapper;
    @Override
    public ArticleAndTas getArticleDetailById(Long id) {
        // 调用 MyBatis Mapper 方法查询文章详情
        ArticleAndTas articleAndTas = articleMapper.selectArticleDetailById(id);
        List<String> tags = tagMapper.selectArticleTagsByArticleId(articleAndTas.getId());
        articleAndTas.setTags(tags);
        return articleAndTas;
    }

    @Override
    @Transactional
    public ResponseResult updateArticle(AddArticleDto articleDto) {
        //添加 博客
        Article article = BeanCopyUtils.copyBean(articleDto, Article.class);
        Long userId = SecurityUtils.getUserId();
        article.setCreateBy(userId);
        article.setUpdateBy(userId);
        article.setCreateTime(new Date());
        article.setUpdateTime(new Date());

        List<ArticleTag> articleTags = new ArrayList<>();
        for (Long tagId : articleDto.getTags()) {
            ArticleTag articleTag = new ArticleTag(article.getId(), tagId);
            articleTags.add(articleTag);
        }
        //添加 博客和标签的关联
        articleMapper.deleteArticleTaps(article.getId());
        articleTagMapper.saveBatch(articleTags);
        return ResponseResult.okResult();
    }

    @Override
    @Transactional
    public ResponseResult deleteArticle(Long id) {

        // 获取当前用户id作为更新人
        Long userId = SecurityUtils.getUserId();
        // 逻辑删除文章
        articleMapper.deleteArticleById(id, userId, new Date());
        
        return ResponseResult.okResult();
    }
}
